/*
 * Copyright (C) 2012-2013 Michael L.R. Marques
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Contact: michaellrmarques@gmail.com
 */

package com.jm.commons.regex;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

/**
 * A simple regular expressions tester
 * 
 * @author Michael L.R. Marques
 */
public class RegexTester extends javax.swing.JFrame {

    /**
     * Creates new form RegexTester
     */
    public RegexTester() {
        initComponents();
        /*
        try {
            setIconImage(ImageIO.read(getClass().getClassLoader().getResource("com/mlrm/jm/commons/icons/jm_logo_32x32.png")));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        */
        loadRegularExpressions();
    }
    
    /**
     * Loads saved regular expressions
     */
    private void loadRegularExpressions() {
        // 
        if (!new File("./settings").exists()) {
            new File("./settings").mkdir();
        }
        //
        File regexFile = new File("./settings/regex.txt");
        // 
        if (!regexFile.exists()) {
            try {
                regexFile.createNewFile();
            } catch (IOException ioe) {
                JOptionPane.showMessageDialog(this, ioe.getMessage());
                return;
            }
        }
        //
        this.cbxRegex.removeAllItems();
        try {
            try (BufferedReader reader = new BufferedReader(new FileReader(regexFile))) {
                String line = null;
                while((line = reader.readLine()) != null) {
                    this.cbxRegex.addItem(line.replace("\n", ""));
                }
            }
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, ioe.getMessage());
        }
    }
    
    public static void main(String[] args) {
        new RegexTester().setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        btnMatch = new javax.swing.JButton();
        btnReplace = new javax.swing.JButton();
        cbxRegex = new javax.swing.JComboBox();
        btnAddPattern = new javax.swing.JButton();
        btnDeletePattern = new javax.swing.JButton();
        txtMatched = new com.jm.commons.components.textfield.HintJTextField();
        txtReplaced = new com.jm.commons.components.textfield.HintJTextField();
        txtMatching = new com.jm.commons.components.textfield.HintJTextField();
        txtReplacing = new com.jm.commons.components.textfield.HintJTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Regular Expressions Tester");
        setLocationByPlatform(true);
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 1280, 233));
        setMaximumSize(new java.awt.Dimension(1280, 233));
        setMinimumSize(new java.awt.Dimension(461, 233));

        jLabel1.setText("Regular Expressions");

        btnMatch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jm/commons/regex/icons/Match.png"))); // NOI18N
        btnMatch.setAlignmentY(0.0F);
        btnMatch.setContentAreaFilled(false);
        btnMatch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                match(evt);
            }
        });

        btnReplace.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jm/commons/regex/icons/Replace.png"))); // NOI18N
        btnReplace.setContentAreaFilled(false);
        btnReplace.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                replace(evt);
            }
        });

        cbxRegex.setEditable(true);

        btnAddPattern.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jm/commons/regex/icons/Add.png"))); // NOI18N
        btnAddPattern.setToolTipText("Add Regular Expression...");
        btnAddPattern.setAlignmentY(0.0F);
        btnAddPattern.setContentAreaFilled(false);
        btnAddPattern.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addRegex(evt);
            }
        });

        btnDeletePattern.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jm/commons/regex/icons/Delete.png"))); // NOI18N
        btnDeletePattern.setToolTipText("Delete Regular Expression...");
        btnDeletePattern.setContentAreaFilled(false);
        btnDeletePattern.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeRegex(evt);
            }
        });

        txtMatched.setEditable(false);
        txtMatched.setHintText("Matched Text...");

        txtReplaced.setEditable(false);
        txtReplaced.setHintText("Replaced Text...");

        txtMatching.setHintText("Matching Text...");

        txtReplacing.setHintText("Replacing Text...");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(cbxRegex, 0, 389, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnAddPattern, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txtMatching, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(4, 4, 4)))
                        .addGap(2, 2, 2)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnDeletePattern, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnMatch, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                    .addComponent(txtMatched, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtReplacing, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnReplace, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(txtReplaced, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddPattern, btnDeletePattern});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAddPattern, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbxRegex, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnDeletePattern, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtMatching, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnMatch, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMatched, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnReplace, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtReplacing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtReplaced, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void match(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_match
        this.txtMatched.setText("");
        try {
            Matcher matcher = Pattern.compile(this.cbxRegex.getSelectedItem().toString()).matcher(this.txtMatching.getText());
            if (matcher.find()){
                this.txtMatched.setText(matcher.group());
            }
        } catch(PatternSyntaxException pse) {
            JOptionPane.showMessageDialog(this, pse.getMessage());
        }
    }//GEN-LAST:event_match

    private void replace(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_replace
        this.txtReplaced.setText("");
        try {
            Matcher matcher = Pattern.compile(this.cbxRegex.getSelectedItem().toString()).matcher(this.txtMatching.getText());
            if (matcher.find()){
                this.txtReplaced.setText(matcher.replaceAll(this.txtReplacing.getText()));
            }
        } catch(PatternSyntaxException pse) {
            JOptionPane.showMessageDialog(this, pse.getMessage());
        }
    }//GEN-LAST:event_replace

    private void addRegex(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRegex
        File regexFile = new File("./settings/regex.txt");
        // 
        if (!regexFile.exists()) {
            try {
                regexFile.createNewFile();
            } catch (IOException ioe) {
                JOptionPane.showMessageDialog(this, ioe.getMessage());
                return;
            }
        }
        //
        String regularExpressions = this.cbxRegex.getSelectedItem().toString() + "\n";
        for (int i = 0; i < this.cbxRegex.getItemCount(); i++) {
            regularExpressions += this.cbxRegex.getItemAt(i).toString() + "\n";
        }
        // 
        try {
            try (FileWriter writer = new FileWriter(regexFile)) {
                writer.write(regularExpressions);
            }
            loadRegularExpressions();
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, ioe.getMessage());
        }
    }//GEN-LAST:event_addRegex

    private void removeRegex(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRegex
        File regexFile = new File("./settings/regex.txt");
        // 
        if (!regexFile.exists()) {
            JOptionPane.showMessageDialog(this, "Regular Expression Pattern file has not been created.");
            return;
        }
        //
        String regularExpressions = "";
        for (int i = 0; i < this.cbxRegex.getItemCount(); i++) {
            if (!this.cbxRegex.getSelectedItem().toString().equals(this.cbxRegex.getItemAt(i).toString())) {
                regularExpressions += this.cbxRegex.getItemAt(i).toString() + "\n";
            }
        }
        // 
        try {
            try (FileWriter writer = new FileWriter(regexFile)) {
                writer.write(regularExpressions);
            }
            loadRegularExpressions();
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this, ioe.getMessage());
        }
    }//GEN-LAST:event_removeRegex
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddPattern;
    private javax.swing.JButton btnDeletePattern;
    private javax.swing.JButton btnMatch;
    private javax.swing.JButton btnReplace;
    private javax.swing.JComboBox cbxRegex;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private com.jm.commons.components.textfield.HintJTextField txtMatched;
    private com.jm.commons.components.textfield.HintJTextField txtMatching;
    private com.jm.commons.components.textfield.HintJTextField txtReplaced;
    private com.jm.commons.components.textfield.HintJTextField txtReplacing;
    // End of variables declaration//GEN-END:variables
}
